package com.zbkj.client.config;

import com.zbkj.service.service.impl.UserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.CorsFilter;

/**
 * 客户端安全配置（详细版）
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class ClientSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailServiceImpl userDetailService;

    @Autowired
    private CorsFilter corsFilter;

    @Autowired
    private ClientAuthenticationProvider clientAuthenticationProvider;


    /**
     * token认证过滤器
     */
    @Bean
    public ClientJwtAuthenticationTokenFilter clientJwtAuthenticationTokenFilter() {
        return new ClientJwtAuthenticationTokenFilter();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 这里将Spring Security自带的authenticationManager声明成Bean，声明它的作用是用它帮我们进行认证操作，
     * 调用这个Bean的authenticate方法会由Spring Security自动帮我们做认证。
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(clientAuthenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .cors()
            .and()
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
                // 允许 WebSocket 连接匿名访问
                .antMatchers("/ws").permitAll()
                // 数字人视频回调地址
                .antMatchers("/dp/**").permitAll()
                //SSE连接
//                .antMatchers("/api/client/sse/**").permitAll()
//                .antMatchers("/api/client/index/**").permitAll()
                //防盗链接口
                .antMatchers("/api/client/common/proxyImage").permitAll()
                //发现详情接口，agent详情接口，group详情接口，分享使用，去掉鉴权
                .antMatchers("/api/client/discovery/getDetail").permitAll()
                .antMatchers("/api/client/agent/getAgentInfo").permitAll()
                .antMatchers("/api/client/agent/getGroupInfo").permitAll()
                // python调用写入agent和group信息
                .antMatchers("/dr/**").permitAll()
                // 允许登录相关接口匿名访问
                .antMatchers("/api/client/login").permitAll()
                .antMatchers("/api/client/sendCode").permitAll()
                .antMatchers("/api/client/test").permitAll()
                .antMatchers("/api/client/test/public").permitAll()

                // 允许套餐相关接口匿名访问
                .antMatchers("/api/client/package/*").permitAll()
                // 允许 Swagger 相关路径匿名访问
                .antMatchers("/swagger-ui/**", "/swagger-resources/**", "/v2/api-docs", "/webjars/**").permitAll()
                // 允许静态资源匿名访问
                .antMatchers("/**/*.html", "/**/*.js", "/**/*.css", "/**/*.png", "/**/*.jpg", "/**/*.gif", "/favicon.ico").permitAll()
                // 允许 Druid 监控匿名访问
                .antMatchers("/druid/**").permitAll()
                // 允许健康检查匿名访问
                .antMatchers("/actuator/**").permitAll()
                // 允许错误页面匿名访问
                .antMatchers("/error").permitAll()
//                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                // 其他所有请求需要认证
                .anyRequest().authenticated()
            .and()
            .formLogin().disable()
            .httpBasic().disable();
        
        // 添加JWT filter
        http.addFilterBefore(clientJwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);


        http.addFilterBefore(corsFilter, ClientJwtAuthenticationTokenFilter.class);
    }
} 